/**
 * Created by godhh on 2016/12/21.
 */

import angular from 'angular'
import 'apiService'
import _ from 'lodash'

const app = angular.module('ProcessCenter');

app.controller('doneCtrl', ['$rootScope', '$scope', 'api', function ($rootScope, $scope, api) {

    const service = api.getService();

    const { pageIndex, pageSize } = api;

    $scope.Page = {
        filter: {},
        rowNames: 'rows',
        pageIndexName: 'page',
        pageSizeName: 'page-size',
        pagination: {
            params: {},
            total: 0,
            change: function (pageIndex, pageSize) {
                const thiz = $scope.Page;
                thiz.pagination.params[thiz['pageIndexName']] = pageIndex;
                thiz.pagination.params[thiz['pageSizeName']] = pageSize;
                thiz.list();
            }
        },
        impl: {
            filterSearchResult: function (res) {
                const thiz = $scope.Page;
                const items = _.map(res.data.data.data, x => _.merge(x, {orderId: x.id}));
                thiz.setItems(items);
                thiz.pagination.total = res.data.data.total;
            }
        },
        getItems: function () {
            return this[this.rowNames];
        },
        setItems: function (items) {
            this[this.rowNames] = items;
            return this.getItems();
        },
        list: function (pageIndex) {
            const thiz = this;
            thiz.pagination.params[thiz['pageIndexName']] = pageIndex || thiz.pagination.params[thiz['pageIndexName']];
            return service.getDeliveryDones(thiz.getQuery(pageIndex))
                .then(function (res) {
                    return thiz.impl.filterSearchResult(res);
                })
        },
        getQuery: function (pageIndex) {
            return angular.extend({}, this.pagination.params, this.filter,
                {[this['pageIndexName']]: pageIndex === undefined ? this.pagination.params[this['pageIndexName']] : pageIndex});
        },
        reset: function () {
            return this.list(pageIndex);
        },
        init: function () {
            this[this.rowNames] = this[this.rowNames] || [];
            this.pagination.params[this['pageIndexName']] = pageIndex;
            this.pagination.params[this['pageSizeName']] = pageSize;
            return this.reset();
        }
    };

    $scope.search = _.debounce(() => {
        $scope.Page.list(1);
    }, 200);

    $scope.$watch('Page.filter', (newValue, oldValue) => {

        if (!_.eq(newValue, oldValue)) {
            $scope.search();
        }

    }, true);

    $scope.Page.init();


}]);
export default app;
